# -*- coding: utf-8 -*-
'''
@文件    :demo.py
@说明    :接口示例
@时间    :2025/08/10 00:23:41
@作者    :浪晋
@版本    :1.0
'''


from fastapi import APIRouter, File, UploadFile, Form, Body, Path, Query, WebSocket
from fastapi.responses import FileResponse, StreamingResponse
from app.core.routeclass import OperationLogRoute


router = APIRouter(route_class=OperationLogRoute)


@router.post("/test", summary="测试接口", description="这是一个测试接口")
async def test():
    print(1/0)
    return {"msg": "ok"}

@router.get("/path/{id}", summary="路径参数获取", description="下载文件流")
async def get_path_data(
    id: int = Path(..., description="路径参数")
):
    return {"msg": "ok", "path": id}


@router.get("/query", summary="查询参数获取", description="下载文件流")
async def get_query_data(
    age: int = Query(..., description="年龄"),
    name: str = Query(..., description="姓名")
):
    return {"age": age, "name": name}


@router.post("/form", summary="表单参数获取", description="下载文件流")
async def get_form_data(
    name: str = Form(..., description="姓名"),
    age: int = Form(..., description="年龄")
):
    return {"age": age, "name": name}


@router.post("/json", summary="json参数获取", description="下载文件流")
async def get_form_data(
    name: str = Body(..., description="姓名", embed=True),
    age: int = Body(..., description="年龄", embed=True)
):
    return {"age": age, "name": name}


@router.post("/upload",summary="上传文件", description="下载文件流")
async def get_file_data(
    file: UploadFile = File(..., description="文件对象")
):
    # 异步写入文件（推荐使用 async with）
    with open("file_path", "wb") as f:
        # 读取文件内容并写入（同步操作，大文件建议分块）
        content = await file.read()  # 异步读取文件内容
        f.write(content)

    return {"message": "文件上传成功", "filename": file.filename}


@router.get("/download/path", summary="下载文件", description="下载本地文件")
async def download_path_file():
    file_path = "./static/favicon.png"
    return FileResponse(file_path, media_type="image/png")


@router.get("/download/stream", summary="下载文件", description="下载文件流")
async def download_stream_file():
    import io
    data = open("./static/favicon.png","rb").read()
    return StreamingResponse(io.BytesIO(data), media_type="image/png")



# 流式接口
@router.get("/stream", summary="流式响应", description="下载文件流")
async def stream_data():
    import asyncio
    async def generate_data():
        for i in range(10):
            yield f"Chunk {i}\n"
            await asyncio.sleep(1) # 模拟延迟
    return StreamingResponse(generate_data(), media_type="text/plain")


@router.websocket("/ws", name="websocket")
async def websocket_endpoint_controller(
    websocket: WebSocket
):
    # pip install websockets
    # ws://127.0.0.1:8000/ws
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")